package com.example.chatbot.controller;

import com.example.chatbot.entity.ChatInfo;
import com.example.chatbot.entity.MessageVO;
import com.example.chatbot.repository.MemoryChatHistoryRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/chat")
public class ChatController {
    @Autowired
    private MemoryChatHistoryRepository chatHistoryRepository;

    @Autowired
    private ChatClient chatClient;

    @Autowired
    private ChatMemory chatMemory;


    /**
     * 进行对话
     * @param prompt
     * @param chatId
     * @return
     */
    @GetMapping(value = "/stream", produces = "text/html;charset=utf-8")
    public Flux<String> stream(String prompt, String chatId) {
        log.info("进行对话，chatId:{}, prompt:{}", chatId, prompt);
        // 保存会话信息
        chatHistoryRepository.save(chatId, new ChatInfo(chatId, prompt));
        return chatClient.prompt()
                .user(prompt)
                // 获取 chatId 的对话记忆
                .advisors(advisorSpec -> advisorSpec.param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY, chatId))
                .stream()
                .content();
    }

    @GetMapping("/getChatIds")
    public List<ChatInfo> getChatIds() {
        return chatHistoryRepository.getChatList();
    }

    /**
     * 获取所有会话信息
     * @param chatId
     * @return
     */
    @GetMapping("/getChatHistory")
    public List<MessageVO> getChatHistory(String chatId) {
        log.info("获取 chatId:{} 会话信息", chatId);
        List<Message> messages = chatMemory.get(chatId, 20);
        if (messages.isEmpty()) {
            return List.of();
        }
        return messages.stream()
                .map(MessageVO::new)
                .collect(Collectors.toList());
    }

    @GetMapping("/deleteChat")
    public Boolean deleteChat(String chatId) {
        log.info("删除 chatId: {} 会话记录", chatId);
        try {
            // 删除会话记录
            chatMemory.clear(chatId);
            // 删除会话id
            chatHistoryRepository.deletedChatId(chatId);
            return true;
        } catch (Exception e) {
            log.error("删除 chatId: {} 会话信息异常", chatId);
            e.printStackTrace();
            return false;
        }
    }
}
